package com.gavindon.android.view.start

import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Handler
import android.widget.ImageView
import com.gavindon.android.HomeActivity
import com.gavindon.android.R
import com.gavindon.android.base.BaseActivity
import com.gavindon.android.base.SP_TOKEN
import com.gavindon.android.entity.LoginStatus
import com.gavindon.android.network.DataResult
import com.gavindon.android.network.downloadAppUrl
import com.gavindon.android.utils.SpUtils
import com.gavindon.android.utils.requestLoginCode
import com.gavindon.android.viewmodel.HomeViewModel
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.hmsscankit.WriterException
import com.huawei.hms.ml.scan.HmsBuildBitmapOption
import com.huawei.hms.ml.scan.HmsScanBase.QRCODE_SCAN_TYPE
import com.orhanobut.logger.Logger
import org.jetbrains.anko.dip
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.util.*
import kotlin.concurrent.timer

/**
 * description: 使用手机app扫码进行登录
 * Created by liNan on  2022-2-8 14:21
 */

class LoginActivity : BaseActivity() {
    override val layoutId = R.layout.activity_login

    private val ivDownLoadApp: ImageView by lazy {
        findViewById(R.id.iv_down_load)
    }
    private val ivLoginApp: ImageView by lazy {
        findViewById(R.id.iv_login)
    }

    private val msg_login = 0
    private val msg_refresh_qr = 2
    private var qrContent = "%$%$"
    private val mViewModel: HomeViewModel by lazy { getViewModel() }

    private var mLoginTimer: Timer? = null

    private var mRefreshQrTimer: Timer? = null

    override fun onInit(savedInstanceState: Bundle?) {
        LoginStatus.token = ""
        LoginStatus.hasLogin = false
        fetchScanCode()
        generateDownloadQr()
        Handler(this.mainLooper).postDelayed({
            loopLogin()
        }, 3000)
    }


    /**
     * 获取二维码信息
     */
    private fun fetchScanCode() {
        mViewModel.getScanCode().observe(this, {
            if (it is DataResult.Success) {
                if (it.data.scanCode.isNotEmpty()) {
                    generateQR(it.data.scanCode)
                }
            }
        })
    }

    /*生成登录码*/
    private fun generateQR(content: String) {
        try {
            val logoBitmap = BitmapFactory.decodeResource(resources, R.mipmap.logo)
            val options =
                HmsBuildBitmapOption.Creator().setQRLogoBitmap(logoBitmap).create()
            ivLoginApp.post {
                val qrBitmap = ScanUtil.buildBitmap(
                    content,
                    QRCODE_SCAN_TYPE,
                    ivLoginApp.width - dip(30),
                    ivLoginApp.height - dip(30),
                    null
                )
                ivLoginApp.background = BitmapDrawable(qrBitmap)
                qrContent = content
            }

        } catch (e: WriterException) {
        }
    }

    override fun onResume() {
        super.onResume()
//        generateDownloadQr()
    }

    /*生成下载apk码*/
    private fun generateDownloadQr() {
        val url = "http://114.67.232.203/DownloadApp/"
        val logoBitmap = BitmapFactory.decodeResource(resources, R.mipmap.logo)
        val options =
            HmsBuildBitmapOption.Creator().setQRLogoBitmap(logoBitmap).create()
        try {
            //防止获取view宽度为0
            ivDownLoadApp.post {
                // 如果未设置HmsBuildBitmapOption对象，生成二维码参数options置null。
                val qrBitmap = ScanUtil.buildBitmap(
                    downloadAppUrl,
                    QRCODE_SCAN_TYPE,
                    ivDownLoadApp.width - dip(30),
                    ivDownLoadApp.height - dip(30),
                    options
                )
                ivDownLoadApp.background = BitmapDrawable(qrBitmap)
            }

        } catch (e: WriterException) {
            Logger.i(e.message.toString())
        }
    }

    /**
     * 循环请求是否登录成功
     */
    private fun loopLogin() {
        val handler = Handler(this.mainLooper) {

            if (it.what == msg_login) {
                mViewModel.getUserLogin(qrContent).observe(this@LoginActivity, {
                    if (it is DataResult.Success && !it.data.token.isNullOrEmpty()) {
                        SpUtils.put(SP_TOKEN, it.data.token)
                        LoginStatus.token = it.data.token
                        mLoginTimer?.cancel()
                        /*使用token进行获取用户信息*/
                        mViewModel.getUserInfo().observe(this) { userInfoResp ->
                            if (userInfoResp is DataResult.Success) {
                                LoginStatus.hasLogin = true
                                LoginStatus.userInfoResp = userInfoResp.data
                                toast("登录成功")
                                setResult(requestLoginCode)
                                this@LoginActivity.finish()
                            } else {
                                LoginStatus.hasLogin = false
                                toast("登录失败")
                            }
                        }

                    }
                })
            } else {
                fetchScanCode()
            }
            return@Handler true
        }
        mLoginTimer = timer(period = 1500L, action = {
            val msg = handler.obtainMessage(msg_login)
            handler.sendMessage(msg)
        })

        mRefreshQrTimer = timer(initialDelay = 2 * 60 * 1000L, period = 2 * 60 * 1000L, action = {
            val msg = handler.obtainMessage(msg_refresh_qr)
            handler.sendMessage(msg)
        })
    }


    override fun onDestroy() {
        super.onDestroy()
        mRefreshQrTimer?.cancel()
        mLoginTimer?.cancel()
    }
}